<template>
  <div style="margin:15px" v-loading="loading">

    <div class="filter-container">
      <div style="float:left;overflow:hidden;display:flex;">
        <div style="float:left;font-size:16px;align-self:center;"> 角色编码：</div>
        <div style="float:left;margin-right:10px">
          <el-input v-model="searchDate.code" type="text" size="small"></el-input>
        </div>
        <div style="float:left;font-size:16px;align-self:center;"> 角色名称：</div>
        <div style="float:left;margin-right:10px">
          <el-input v-model="searchDate.name" type="text" size="small"></el-input>
        </div>
      </div>
      <div style="float:left;margin-left:20px">
        <el-button class="filter-item" type="primary" icon="el-icon-search" size="small" @click="query">搜索
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" size="small" icon="el-icon-edit"
                   @click="handleAddClick">添加
        </el-button>
      </div>
    </div>

    <el-table :data="tableData" border stripe highlight-current-row>
      <el-table-column type="index" :index="indexMethod" width="50"></el-table-column>
      <el-table-column header-align="center" align="left" width="200" prop="code" label="角色编码"></el-table-column>
      <el-table-column header-align="center" align="left" width="200" prop="name" label="角色名称"></el-table-column>
      <el-table-column header-align="center" align="left" width="200" prop="remark" label="角色描述"></el-table-column>
      <el-table-column header-align="center" align="center" width="100" prop="email" label="角色用户">
        <template slot-scope="scope">
          <el-button @click="showRoleUsers(scope.row)" size="small">用户</el-button>
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="center" width="100" prop="email" label="角色权限">
        <template slot-scope="scope">
          <el-button @click="editPermission(scope.row)" size="small">权限</el-button>
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="center" width="160" prop="" label="操作">
        <template slot-scope="scope">
          <el-button @click.native="handleEditClick(scope.row)" size="small">编辑</el-button>
          <el-button @click.native="handleDeleteClick(scope.row)" size="small">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="left" width="" prop="" label=""></el-table-column>
    </el-table>

    <div style="margin: 20px;overflow: hidden">
      <div style="text-align: center;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="pageCurrent"
          :page-sizes="[5,10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, prev, pager, next, sizes"
          :total="totalSize">
        </el-pagination>
      </div>
    </div>

    <el-dialog title="角色信息" :visible.sync="dialogFormVisible" :before-close="beforeClose" width="30%">
      <el-form :model="form" ref="form" :rules="rules">
        <el-form-item label="角色编码：" :label-width="formLabelWidth" prop="code">
          <el-input v-model="form.code" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色名称：" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述：" :label-width="formLabelWidth">
          <el-input type="textarea" :rows="3" v-model="form.remark" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormClose">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="角色用户" :visible.sync="dialogTableVisible" width="25%">
      <el-table :data="gridData" border style="max-height:400px;overflow: auto;">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column property="username" label="登录账号"></el-table-column>
        <el-table-column property="jobNo" label="用户工号"></el-table-column>
        <el-table-column property="name" label="用户姓名"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="dialogTableVisible=false">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog title="角色-权限设置" :visible.sync="dialogTreeVisible" width="60%">
      <el-container style="height: 400px; border: 1px solid #eee">
        <el-aside style="border-right: 1px solid #eee; width: 200px;">
          <el-tree
            :data="treeData"
            ref="menuTree"
            :props="defaultProps"
            @node-click="handleNodeClick"
            show-checkbox
            node-key="dbid"
            :expand-on-click-node="false"
          ></el-tree>
        </el-aside>
        <el-main>
          <el-table :data="permissionData" ref="permissionTable" @select="handlePerSelectChange" @select-all="handlePerSelectAllChange"
                    @cell-click="cellClickEvent" border>
            <el-table-column align="center" type="selection" width="50"></el-table-column>
            <el-table-column type="index" width="50"></el-table-column>
            <el-table-column property="code" label="权限编码"></el-table-column>
            <el-table-column property="name" label="权限名称"></el-table-column>
            <el-table-column property="url" label="URL"></el-table-column>
            <el-table-column property="expname" label="表达式">
              <template slot-scope="scope">
                <span v-if="!scope.row.editable">{{ scope.row.expname }}</span>
                <el-select v-if="scope.row.editable" placeholder="请选择" v-model="scope.row.expId" clearable
                           @change="selectExp($event,scope.row)">
                  <el-option v-for="item in expItems" :key="item.dbid" :label="item.expname" :value="item.dbid"></el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
      </el-container>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTreeVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRolePurview">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {
    getRoleInfoList,
    saveRoleInfo,
    deleteRoleById,
    getRoleStaffList,
    // getRoleMenus,
    getRolePermission,
    saveRolePurview,
    // getExpByPermissionid
  } from 'api/role';
  import { getObj,getExp,getTreeMenu } from 'api/menu'

  export default {
    data() {
      return {
        allData: [],//加载数据
        tableData: [],//加载数据
        gridData: [],
        permissionData: [],
        editPermissionIdx: -1,
        treeData: [],
        treeSelect: [],
        expItems: [],
        rolePermission: [],
        defaultProps: {label: 'name', children: 'children'},
        rpData: {roleId: '', delRpid: [], addExpId: [], addType: [], addPid: [], addRpid: []},
        totalSize: 0,
        pageSize: 5,//每页显示的条数
        pageCurrent: 1,//第几页
        searchDate: {code: '', name: ''},
        loading: false,
        dialogFormVisible: false,  //增加编辑层
        dialogTableVisible: false,
        dialogTreeVisible: false,
        editRoleId: '',
        formLabelWidth: '100px',
        form: {dbid: '', roleCode: '', roleName: '', description: '', status: '0'},
        rules: {
          roleCode: [
            {required: true, message: '请输入角色编码', trigger: 'blur'}
          ],
          roleName: [
            {required: true, message: '请输入角色名称', trigger: 'blur'}
          ]
        }
      }
    },
    methods: {
      query(){
        this.pageCurrent = 1;
        this.searchData();
      },
      //点击分页前进后退或页数时触发的方法
      handleSizeChange(val) {
        this.pageSize = val;
        this.searchData();
      },
      //选择每页显示条数触发的方法
      handleCurrentChange(val) {
        this.pageCurrent = val;
        this.searchData()
      },
      indexMethod(index) {
        return (this.pageCurrent - 1) * this.pageSize + 1 + index;
      },
      handleAddClick() {
        this.dialogFormVisible = true;
      },
      showRoleUsers(role) {
        getRoleStaffList(role.dbid).then(info => {
          this.gridData = info.data;
        });
        this.dialogTableVisible = true;
      },
      editPermission(role) {
        this.editRoleId = role.dbid;
        this.rpData = {roleId: role.dbid, delRpid: [], addExpId: [], addType: [], addPid: [], addRpid: []};
        this.treeData = [{
          dbid: 0,
          code: 'ROOT',
          name: '系统模块',
          parentId: '',
          type: '00',
          url: '',
          purviewId: '',
          expId: '',
          expname: '',
          disabled: true,
          children: []
        }];
        this.permissionData = [];
        this.treeSelect = [];
        this.dialogTreeVisible = true;
        let data = {roleId:role.dbid,type:'00'};

        getRolePermission(data).then(res1 => {//获取角色已经分配的菜单，
          getTreeMenu(0).then(res => {
            if(res.data.length > 0){
              res1.data.forEach(item1 => {
                this.defTreeSelect(res.data,item1.dbid)
              });
              this.$set(this.treeData[0], 'children', res.data)
              this.$nextTick(function() {
                this.$refs.menuTree.setCheckedKeys(this.treeSelect);
              })
            }
          })
        });
        let data2 = {roleId:role.dbid,type:'01'};
        getRolePermission(data2).then(res => {//获取角色已经分配的权限点
          this.rolePermission = res.data
        })
      },
      defTreeSelect(data,dbid) {//把已经分配的叶子菜单dbid放到this.treeSelect
        data.forEach(d => {
          if (d.children) {
            this.defTreeSelect(d.children,dbid);
          } else if (d.dbid == dbid) {
            this.treeSelect.push(d.dbid);
          }
        });
      },
      handleNodeClick(data) {
        let that_ = this;
        if(data.children===null){
          that_.permissionData=[];
          getObj(data.dbid,'01').then( res => {
            if(res.data.length > 0){
              that_.permissionData = res.data;
              this.$nextTick(function () {
                this.permissionData.forEach(item => {
                  this.rolePermission.forEach(item2 => {
                    if (item.dbid === item2.dbid) {
                      item.expid = item2.expid
                      item.expname = item2.expname
                      this.$refs.permissionTable.toggleRowSelection(item, true)
                    }
                  })
                })
              })
            }
          })
        }
      },
      cellClickEvent(row, column, cell, event) {
        // this.hideExpSelector();
        if (column.label === '表达式') {
          this.expItems = [];
          getExp(row.dbid).then(res =>{
            this.expItems = res.data;
          })
          let idx = 0;
          for (; idx < this.permissionData.length; idx++) {
            if (this.permissionData[idx].dbid === row.dbid) {
              break;
            }
          }
          // this.editPermissionIdx = idx;
          this.permissionData[idx].editable = true;
          this.$set(this.permissionData, idx, this.permissionData[idx]);
        }
      },
      /*hideExpSelector() {
        if (this.editPermissionIdx !== -1) {
          this.permissionData[this.editPermissionIdx].editable = false;
          this.$set(this.permissionData, this.editPermissionIdx, this.permissionData[this.editPermissionIdx]);
          this.editPermissionIdx = -1;
        }
      },*/
      selectExp(val, row) {
        row.expid = val;
        this.rolePermission.forEach(item =>{
          if(item.dbid===row.dbid){
            item.expid = val
            // item.expname = row.expname
          }
        });
        /*this.expItems.forEach(d => {
          if (d.dbid === data) {
            this.permissionData[this.editPermissionIdx].expname = d.expname;
          }
        });*/
      },
      /*defTableSelect() {
        setTimeout(() => {
          this.permissionData.forEach(d => {
            this.$refs.permissionTable.toggleRowSelection(d, d.selected);
          });
        }, 5);
      },*/
     /* handleSelectionChange(selection, row) {
        this.permissionData.forEach(d => {
          d.selected = false;
        });
        selection.forEach(d => {
          d.selected = true;
        });
      },*/
      handlePerSelectChange(selection, row){
        this.handlePerSelectionChange(selection);

      },
      handlePerSelectAllChange(selection){
        this.handlePerSelectionChange(selection);
      },
      handlePerSelectionChange(val){
        //将数据删除 在加入新选中的
        let permissionTableData = this.permissionData;
        let rolePermission = this.rolePermission;
        for (let i = 0; i < permissionTableData.length; i++) {
          let datai = permissionTableData[i];
          for (let j = 0; j < rolePermission.length; j++) {
            let perj = rolePermission[j];
            if (datai.dbid == perj.dbid) {
              rolePermission.splice(j, 1);
            }
          }
        }
        this.rolePermission  = rolePermission.concat(val);
      },

      /*checkTreeSelect(checkedKeys, data) {
        data.forEach(d => {
          let idx = checkedKeys.indexOf(d.dbid);
          if (d.purviewId && idx === '0') {
            this.rpData.delRpid.push(d.purviewId);
          }
          if (!d.purviewId && idx !== '0') {
            this.rpData.addPid.push(d.dbid);
            this.rpData.addType.push('00');
            this.rpData.addExpId.push(0);
            this.rpData.addRpid.push(null);
          }
          if (d.permissionData) {
            d.permissionData.forEach(p => {
              if (!p.selected && p.purviewId) {  //删除权限
                this.rpData.delRpid.push(p.purviewId);
              }
              if ((!p.purviewId && p.selected) || (p.purviewId && p.selected && p.expId !== p.old_expId)) {  //新增权限或修改表达式
                this.rpData.addPid.push(p.dbid);
                this.rpData.addType.push('01');
                this.rpData.addExpId.push(p.expId);
                this.rpData.addRpid.push(p.purviewId);
              }
            });
          }
          if (d.children) {
            this.checkTreeSelect(checkedKeys, d.children);
          }
        });
      },*/
      saveRolePurview() {
        this.loading = true;
        let checkedKeys = this.$refs.menuTree.getCheckedKeys();
        let halfCheckedKeys = this.$refs.menuTree.getHalfCheckedKeys();
        let keys = checkedKeys.concat(halfCheckedKeys);
        let rolePermissions = [];
        keys.forEach(dbid =>{
          if(dbid!==0){
            rolePermissions.push({roleDbid:this.editRoleId,permissionDbid:dbid})
          }
        });
        this.rolePermission.forEach(item =>{
          rolePermissions.push({roleDbid:this.editRoleId,permissionDbid:item.dbid,formula:item.expid})
        });
        saveRolePurview(rolePermissions).then(res => {
          this.dialogTreeVisible = false;
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        });
      },
      handleEditClick(data) {
        this.dialogFormVisible = true;
        this.form = data;
        this.form.old_password = data.password;
      },
      handleDeleteClick(data) {
        this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true;
          deleteRoleById(data.dbid).then(res => {
            this.loading = false;
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.searchData();
          }).catch(() => {
            this.loading = false;
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      searchData() {
        let start = this.pageCurrent;
        let limit = this.pageSize
        getRoleInfoList(this.searchDate.code, this.searchDate.name, start, limit).then(res => {
          this.tableData = res.data;
          this.totalSize = res.totalCount;//确认总数
        });
      },
      saveRoleInfo() {
        this.$refs.form.validate(valid => {
          if (valid) {
            this.loading = true;
            saveRoleInfo(this.form).then(res => {
              this.loading = false;
              this.dialogFormClose();
              this.searchData();
            }).catch(() => {
              this.loading = false;
            });
          } else {
            this.$message({
              type: 'error',
              message: '请正确填写表单数据!'
            });
            return false;
          }
        });
      },
      dialogFormClose() {
        this.form = {dbid: '', roleCode: '', roleName: '', description: '', status: '0'};
        this.$refs.form.resetFields();
        this.dialogFormVisible = false;
      },
      beforeClose(done) {
        this.form = {dbid: '', roleCode: '', roleName: '', description: '', status: '0'};
        this.$refs.form.resetFields();
        done();
      }
    },
    created() {
      this.searchData();
    },
    mounted() {

    },
    computed: {}
  }
</script>
